package com.rocksdata.mc.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.ctz.commonframe.constant.DeviceInfo;
import com.ctz.commonframe.ui.WebViewActivity;
import com.ctz.commonframe.ui.view.DragGridView;
import com.ctz.commonframe.ui.view.EmbeddedGridView;
import com.ctz.commonframe.ui.view.EmbeddedListView;
import com.ctz.commonframe.ui.widget.AbsAdapter;
import com.ctz.commonframe.ui.widget.AdapterViewHolder;
import com.ctz.commonframe.utils.DensityUtil;
import com.ctz.commonframe.utils.GlideApp;
import com.ctz.commonframe.utils.Logger;
import com.rocksdata.mc.R;
import com.rocksdata.mc.business.BusinessManager;
import com.rocksdata.mc.business.CampusAppManager;
import com.rocksdata.mc.entity.CampusAppInfo;
import com.ctz.commonframe.ui.TitleBarActivity;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * Created by 陈堂正 on 2016/11/24.
 */

@ContentView(R.layout.activity_campus_app2)
public class AppManagerActivity2 extends TitleBarActivity {
    @ViewInject(R.id.tv_app_manager)
    private TextView tvManager;
    @ViewInject(R.id.gv_homepage_app)
    private EmbeddedGridView gvHomepageApp;
//    @ViewInject(R.id.tv_selected_app)
//    private TextView tvSelectedApp;
//    @ViewInject(R.id.et_campus_app_search)
    private EditText etSearch;
    @ViewInject(R.id.layout_app_manager)
    private LinearLayout layoutAppManager;
    @ViewInject(R.id.gv_app_search_result)
    private EmbeddedGridView gvSearchResult;
    @ViewInject(R.id.gv_selected_app)
    private DragGridView gvSelectedApp;
    @ViewInject(R.id.lv_app)
    private EmbeddedListView lvApp;
    @ViewInject(R.id.tv_label)
    private TextView tvHomepageLabel;
    @ViewInject(R.id.iv_ellipsize)
    private ImageView ivEllipsize;

    private boolean isModifyMode;
    private List<CampusAppInfo> allAppList;
    private List<String> homepageAppCodeList;
    private List<CampusAppInfo> selectedAppList = new ArrayList<>();
    private AppGridAdapter selectedAdapter;
    private List<Map<String, List<CampusAppInfo>>> appGroupMapList = new ArrayList<>();
    private AppAdapter appAdapter;
    private List<CampusAppInfo> searchResultList = new ArrayList<>();
    private SearchAppResultAdapter searchAdapter;
    private HomepageAppIconAdapter homepageAppIconAdapter;
    private int gridWidth;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        etSearch = new EditText(this);
        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
        int vMargin = DensityUtil.dip2px(this, 5);
        int hMargin = DensityUtil.dip2px(this, 40);
        lp.setMargins(hMargin, vMargin, hMargin, vMargin);
        etSearch.setGravity(Gravity.CENTER_VERTICAL);
        etSearch.setBackgroundResource(R.drawable.bg_search_edit);
        etSearch.setHint("应用名称");
        etSearch.setTextSize(14);
        etSearch.setPadding(10, 12, 10, 12);
        etSearch.setCompoundDrawablePadding(10);
        etSearch.setCompoundDrawablesRelativeWithIntrinsicBounds(R.mipmap.ic_search, 0, 0, 0);
        etSearch.setFocusable(true);
        setTitleMiddleView(etSearch, lp);

        allAppList = BusinessManager.getApplicationManager().getAllAppList();
        homepageAppCodeList = CampusAppManager.getHomepageAppCodes();
        handleAppList();
        selectedAdapter = new AppGridAdapter(this, selectedAppList, isModifyMode, true);
        gvSelectedApp.setAdapter(selectedAdapter);
        reMesureGridViewHeight(gvSelectedApp);
        gvSelectedApp.setOnChangeListener(new DragGridView.OnChanageListener() {
            @Override
            public void onChange(int from, int to) {
                CampusAppInfo temp = selectedAppList.get(from);
                if(from < to){
                    for(int i = from; i < to; i++){
                        Collections.swap(selectedAppList, i +1, i);
                    }
                }else if(from > to){
                    for(int i = from; i > to; i--){
                        Collections.swap(selectedAppList, i-1, i);
                    }
                }
                selectedAppList.set(to, temp);
                selectedAdapter.notifyDataSetChanged();
            }
        });
        gvSelectedApp.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                CampusAppInfo info = selectedAdapter.getItem(position);
                if(info != null){
                    if(isModifyMode) {
                        removeApp(info);
                    }
                }
            }

        });

        appAdapter = new AppAdapter(this, appGroupMapList);
        lvApp.setAdapter(appAdapter);

        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() == 0) {
                    gvSearchResult.setVisibility(View.GONE);
                    layoutAppManager.setVisibility(View.VISIBLE);
                    selectedAdapter.notifyDataSetChanged();
                    appAdapter.notifyDataSetChanged();
                    hideKeyboard(etSearch);
                } else {
                    gvSearchResult.setVisibility(View.VISIBLE);
                    layoutAppManager.setVisibility(View.GONE);
                    searchResultList.clear();
                    for(CampusAppInfo info: allAppList){
                        if(info.getName().contains(s)){
                            searchResultList.add(info);
                        }
                    }
                    searchAdapter = new SearchAppResultAdapter(AppManagerActivity2.this, searchResultList, isModifyMode);
                    gvSearchResult.setAdapter(searchAdapter);
                    gvSearchResult.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            CampusAppInfo info = searchAdapter.getItem(position);
                            if(info != null){
                                if(isModifyMode) {
                                    if(homepageAppCodeList.contains(info.getCode())){
                                        selectedAppList.remove(info);
                                    }else{
                                        selectedAppList.add(info);
                                    }
                                    searchAdapter.notifyDataSetChanged();
                                }else{
                                    CampusAppManager.skipToChildApplication(AppManagerActivity2.this, info);
                                }
                            }
                        }
                    });
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        int space = DensityUtil.dip2px(AppManagerActivity2.this, 16);
        tvHomepageLabel.measure( 0,  0);
        int labelWidth = gvHomepageApp.getMeasuredWidth();
        tvManager.measure( 0,  0);
        int managerWidth = tvManager.getMeasuredWidth();
        gridWidth = DeviceInfo.screenWidth - labelWidth - managerWidth - 5 * space;
        onModifyModeChanged();
    }

    private void onModifyModeChanged(){
        tvManager.setText(isModifyMode ? "完成" : "编辑");
        gvSelectedApp.setVisibility(isModifyMode ? View.VISIBLE : View.GONE);
        if(selectedAdapter != null)
            selectedAdapter.setModifyMode(isModifyMode);
        if(appAdapter != null)
            appAdapter.setModifyMode(isModifyMode);
        updateSelectedApp();
        updateAppChecked();
    }

    private void handleAppList(){
        selectedAppList.clear();
        Map<String, List<CampusAppInfo>> appGroupMap = new LinkedHashMap<>();
        for(CampusAppInfo info: allAppList){
            List<CampusAppInfo> list = appGroupMap.get(info.getGroup());
            if (list == null) {
                list = new ArrayList<>();
                appGroupMap.put(info.getGroup(), list);
            }
            list.add(info);
            Collections.sort(list, new Comparator<CampusAppInfo>(){
                @Override
                public int compare(CampusAppInfo info1, CampusAppInfo info2) {
                    return info2.getIs_usable() - info1.getIs_usable();
                }
            });

            if(homepageAppCodeList.contains(info.getCode())){
                selectedAppList.add(info);
            }
        }
        for (String group: appGroupMap.keySet()) {
            Map<String, List<CampusAppInfo>> map = new HashMap<>();
            map.put(group, appGroupMap.get(group));
            appGroupMapList.add(map);
        }
    }

    @Event(value = {R.id.iv_back, R.id.tv_app_manager})
    private void OnClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_app_manager:
                isModifyMode = !isModifyMode;
                onModifyModeChanged();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data != null){
            boolean relogin = data.getBooleanExtra(WebViewActivity.EXTRA_KEY_RELOGIN, false);
            if (relogin) {
                BusinessManager.getAccountManager().logout();
                exit();
                startActivityForResult(new Intent(AppManagerActivity2.this, LoginActivity.class), 1234);
                return;
            }
        }
    }

    private void updateSelectedApp(){
//        gvHomepageApp.setNumColumns(5);

        int padding = DensityUtil.dip2px(AppManagerActivity2.this, 4);
        int iconWidth = DensityUtil.dip2px(AppManagerActivity2.this, 24) + padding * 2;
        int column = gridWidth / iconWidth;
        if (column <= selectedAppList.size()) {
            column--;
            ivEllipsize.setVisibility(View.VISIBLE);
        }else{
            ivEllipsize.setVisibility(View.GONE);
        }
        Logger.e("gridview column:" + column);
        gvHomepageApp.setNumColumns(column);
        if (homepageAppIconAdapter == null) {
            homepageAppIconAdapter = new HomepageAppIconAdapter(AppManagerActivity2.this, selectedAppList);
            homepageAppIconAdapter.setCount(column);
            gvHomepageApp.setAdapter(homepageAppIconAdapter);
        } else {
            homepageAppIconAdapter.setCount(column);
            homepageAppIconAdapter.notifyDataSetChanged();
        }
//        tvSelectedApp.setText("");
//        int wordWidth = DensityUtil.sp2px(AppManagerActivity2.this, 16);
//        int textWidth = DeviceInfo.screenWidth - 16 * 4 - wordWidth * 6;
//        int totalWidth = 0;
//        String htmlEllipsize = "<img src='" + R.mipmap.ic_ellipsize + "'/>";
//        CampusAppImage imgEllipsize = new CampusAppImage(AppManagerActivity2.this);
//        CharSequence ellipsize = Html.fromHtml(htmlEllipsize, imgEllipsize, null);
//        int ellipsizeWidth = imgEllipsize.getWidth();
//        for(CampusAppInfo info: selectedAppList){
//            String html = "<img src='" + info.getIcon() + "'/>";
//            CampusAppImage imgGetter = new CampusAppImage(AppManagerActivity2.this);
//            CharSequence charSequence = Html.fromHtml(html, imgGetter, null);
//            int currentWidth = imgGetter.getWidth() + wordWidth / 2;
//            totalWidth += currentWidth;
//            if (textWidth - totalWidth > ellipsizeWidth + currentWidth) {
//                tvSelectedApp.append(charSequence);
//                tvSelectedApp.append(" ");
//            } else {
//                tvSelectedApp.append(ellipsize);
//                break;
//            }
//        }
    }

    private class HomepageAppIconAdapter extends AbsAdapter<CampusAppInfo> {
        private int column;

        public HomepageAppIconAdapter(Context context, List<CampusAppInfo> datas) {
            super(context, datas, R.layout.item_homepage_app);
        }

        @Override
        public int getCount() {
            return datas.size() < column ? datas.size(): column;
        }

        public void setCount(int column) {
            this.column = column;
        }

        @Override
        public void convert(AdapterViewHolder holder, CampusAppInfo data) {
            ImageView icon = holder.getView(R.id.iv_homepage_app);
            GlideApp.with(context).load(data.getIcon()).into(icon);
        }
    }

    private class CampusAppImage implements Html.ImageGetter {
        private int width;
        private int height;
        private Context context;

        CampusAppImage(Context context){
            this.context = context;
        }

        public int getWidth() {
            return width;
        }

        public int getHeight() {
            return height;
        }

        @Override
        public Drawable getDrawable(String source) {
            try {
                @SuppressWarnings("deprecation")
                Drawable d = GlideApp.with(context)
                        .asDrawable()
                        .load(source)
                        .into(50, 50)
                        .get();
                width = d.getIntrinsicWidth();
                height = d.getIntrinsicHeight();
//                d.setBounds(0, 0, width, height);
                return d;
            } catch (Exception e) {
                return null;
            }
        }
    }

    private void updateAppChecked(){
        CampusAppManager.saveHomepageApps(selectedAppList);
    }

    private void addApp(CampusAppInfo info){
        if(!info.usable()) return;
        if (selectedAppList.size() == 11){
            showToast("首页最多11个应用");
        } else {
            homepageAppCodeList.add(info.getCode());
            selectedAppList.add(info);
            selectedAdapter.notifyDataSetChanged();
            appAdapter.notifyDataSetChanged();
            reMesureGridViewHeight(gvSelectedApp);
        }
    }

    private void removeApp(CampusAppInfo info){
        if(!info.usable()) return;
        homepageAppCodeList.remove(info.getCode());
        selectedAppList.remove(info);
        selectedAdapter.notifyDataSetChanged();
        appAdapter.notifyDataSetChanged();
        reMesureGridViewHeight(gvSelectedApp);
    }

    private class AppAdapter extends AbsAdapter<Map<String, List<CampusAppInfo>>> {
        private boolean isModifyMode;

        AppAdapter(Context context, List<Map<String, List<CampusAppInfo>>> dataList) {
            super(context, dataList, R.layout.item_app);
        }

        void setModifyMode(boolean isModifyMode){
            if(this.isModifyMode != isModifyMode) {
                this.isModifyMode = isModifyMode;
                notifyDataSetChanged();
            }
        }

        @Override
        public void convert(final AdapterViewHolder holder, final Map<String, List<CampusAppInfo>> data) {
            TextView type = holder.getView(R.id.tv_app_type_label);
            EmbeddedGridView gridView = holder.getView(R.id.gv_app);
            String group = data.keySet().iterator().next();
            type.setText(group);
            final List<CampusAppInfo> list = data.get(group);
            AppGridAdapter adapter = new AppGridAdapter(context, list, isModifyMode, false);
            gridView.setAdapter(adapter);
            gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    if(position < list.size()) {
                        if (isModifyMode) {
                            if (!homepageAppCodeList.contains(list.get(position).getCode())) {
                                addApp(list.get(position));
                            }
                        }else{
                            CampusAppManager.skipToChildApplication(context, list.get(position));
                        }
                    }
                }
            });
        }
    }

    private class AppGridAdapter extends AbsAdapter<CampusAppInfo>{
        private boolean isModifyMode;
        private boolean isSelectedType;
        private int mHideItemPosition = -1;

        void setModifyMode(boolean isModifyMode){
            if(this.isModifyMode != isModifyMode) {
                this.isModifyMode = isModifyMode;
                notifyDataSetChanged();
            }
        }

        AppGridAdapter(Context context, List<CampusAppInfo> dataList, boolean isModifyMode, boolean isSelectedType) {
            super(context, dataList, R.layout.item_app_grid);
            this.isModifyMode = isModifyMode;
            this.isSelectedType = isSelectedType;
        }

        @Override
        public void convert(AdapterViewHolder holder, CampusAppInfo data) {
            TextView name = holder.getView(R.id.tv_app_name);
            ImageView icon = holder.getView(R.id.iv_app_icon);
            ImageView flag = holder.getView(R.id.iv_app_control);
            if(data != null) {
                name.setText(data.getName());
                GlideApp.with(context).load(data.getIcon()).into(icon);
                flag.setVisibility(isModifyMode && data.usable() ? View.VISIBLE : View.GONE);
                if (homepageAppCodeList.contains(data.getCode())) {
                    if (isSelectedType)
                        flag.setImageResource(R.mipmap.ic_app_remove);
                    else
                        flag.setImageResource(R.mipmap.ic_app_selected);
                } else {
                    flag.setImageResource(R.mipmap.ic_app_add);
                }
            }
            holder.getConvertView().setLayoutParams(new AbsListView.LayoutParams(
                    AbsListView.LayoutParams.MATCH_PARENT, DeviceInfo.screenWidth / 4));

            if(holder.getPosition() == mHideItemPosition){
                holder.getConvertView().setVisibility(View.INVISIBLE);
            }
        }

//        @Override
//        public void reorderItems(int oldPosition, int newPosition) {
//            Logger.e("oldPosition:" + oldPosition + ",newPosition:" + newPosition);
//            CampusAppInfo temp = datas.get(oldPosition);
//            if(oldPosition > newPosition){
//                for(int i = oldPosition; i < newPosition; i++){
//                    Collections.swap(datas, i +1, i);
//                }
//            }else if(oldPosition < newPosition){
//                for(int i = oldPosition; i > newPosition; i--){
//                    Collections.swap(datas, i-1, i);
//                }
//            }
//            Logger.e("drag, oldPosition item:" + datas.get(oldPosition).getName());
////            datas.set(oldPosition, datas.get(newPosition));
//            datas.set(newPosition, temp);
//            notifyDataSetChanged();
//        }
//
//        @Override
//        public void setHideItem(int hidePosition) {
////            mHideItemPosition = hidePosition;
////            notifyDataSetChanged();
//        }
    }

    private class SearchAppResultAdapter extends AbsAdapter<CampusAppInfo>{
        private boolean isModifyMode;

        SearchAppResultAdapter(Context context, List<CampusAppInfo> dataList, boolean isModifyMode){
            super(context, dataList, R.layout.item_app_grid);
            this.isModifyMode = isModifyMode;
        }

        @Override
        public void convert(AdapterViewHolder holder, CampusAppInfo data) {
            TextView name = holder.getView(R.id.tv_app_name);
            ImageView icon = holder.getView(R.id.iv_app_icon);
            ImageView flag = holder.getView(R.id.iv_app_control);
            if(data != null) {
                name.setText(data.getName());
                GlideApp.with(context).load(data.getIcon()).into(icon);
                if(isModifyMode && data.usable()){
                    flag.setVisibility(View.VISIBLE);
                    if (homepageAppCodeList.contains(data.getCode())) {
                        flag.setImageResource(R.mipmap.ic_app_remove);
                    } else {
                        flag.setImageResource(R.mipmap.ic_app_add);
                    }
                }else{
                    flag.setVisibility(View.GONE);
                }
            }
            holder.getConvertView().setLayoutParams(new AbsListView.LayoutParams(
                    AbsListView.LayoutParams.MATCH_PARENT, DeviceInfo.screenWidth / 4));
        }
    }

    public void reMesureGridViewHeight(DragGridView gridView) {
        int rows;
        int size = selectedAppList.size();
        if (size % 4 == 0) {
            rows = size / 4;
        } else {
            rows = size / 4 + 1;
        }
        LinearLayout.LayoutParams p = (android.widget.LinearLayout.LayoutParams) gridView
                .getLayoutParams();
        int w = View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED);
        int h = View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED);
        gridView.measure(w, h);
        int height = gridView.getMeasuredHeight();
        p.height = height * rows;
        gridView.setLayoutParams(p);
    }
}
